<template>
  <div class="only-office-editor">
    <DocumentEditor
        v-if="initFinish"
        id="docEditor"
        ref="officeEditor"
        :config="config"
        :documentServerUrl="onlyOfficeServerUrl"
        :events_onAppReady="handleAppReadyCallback"
        :events_onDocumentStateChange="handleDocumentStateChange"
        class="onlyOfficeEditor"
    />
  </div>

</template>

<script lang="ts" setup>

import {DocumentEditor, IConfig} from "@onlyoffice/document-editor-vue";
import {onMounted, ref, defineEmits, onBeforeUnmount} from "vue";
import {getUserInfo} from "@/utils/system";
import {getConfig, getServerUrl} from "@/api/documentManage/onlyOfficeManager";
import {isAppCollapsed} from "@/main";
import {useRoute} from "vue-router";
import {message} from "@/utils/ElmessasgeUtils";

const route = useRoute()
const fileName = route.query.fileName as string;
const filePath = route.query.filePath as string;
const bucket = route.query.bucket as string;

// 确保正确声明 ref 类型
const officeEditor = ref<InstanceType<typeof DocumentEditor> | null>(null);
const config = ref<IConfig>({})
const onlyOfficeServerUrl = ref('')
const initFinish = ref(false)

const emit = defineEmits(['document-state-change'])


const handleDocumentStateChange = () => {
  console.log("文件版本发生变化")
  emit('document-state-change')
}

function handleAppReadyCallback() {
  console.log("文件已经就绪")
}

function getOnlyOfficeConfig(filePath: string, fileName: string) {

  let userInfo = getUserInfo()
  let username = 'tmpUser'
  let userId = -1


  if (userInfo.username != '') {
    username = userInfo.username;
    userId = userInfo.userId;
  }
  // 构建入参
  let param = {
    "fileName": fileName,
    "filePath": filePath,
    "bucket": bucket,
    "model": "edit",
    "userId": userId,
    "user": {
      "name": username,
      "id": userId
    }
  }

  console.log("入参：" + JSON.stringify(param))

  getConfig(param).then((res: any) => {
    if (res.data.code === 200) {
      config.value = JSON.parse(res.data.data);
      initFinish.value = true;
    }
  })

}

onMounted(() => {

  getServerUrl().then((res: any) => {
    if (res.data.code === 200) {
      onlyOfficeServerUrl.value = res.data.data;
    } else {
      message("获取minio地址失败", 'error');
    }
  })

  isAppCollapsed.value = true;
  getOnlyOfficeConfig(filePath, fileName)
})

onBeforeUnmount(() => {
  isAppCollapsed.value = false;
})

</script>

<style scoped>

.only-office-editor {
  width: 100%;
  height: 100%;
}

.onlyOfficeEditor {
  width: 100%;
  height: 100%;
}
</style>